package com.shanghaionstar.discover.presenter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentManager;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.RequestStatus;
import com.onstar.cn.vehicle.result.PollingResult;
import com.shanghaionstar.R;
import com.shanghaionstar.discover.iview.IWifiHomeView;
import com.shanghaionstar.discover.model.WifiInfoModel;
import com.shanghaionstar.discover.service.WifiHomeService;
import com.shanghaionstar.login.register.JoinMeUtils;
import com.shanghaionstar.pin.PinDialogFragment;
import com.shanghaionstar.pin.model.PinModel;
import com.shanghaionstar.service.VehiclePollingService;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;

import org.json.JSONObject;

import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 7828wc on 16/7/27.
 */
public class WifiHomePresenter extends BasePresenter<WifiInfoModel> {
    private IWifiHomeView view;
    private WifiHomeService service;

    public WifiHomePresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        this.view = (IWifiHomeView) view;
        service = new WifiHomeService(view.onActivity());
    }

    private boolean checkRole(Context context) {
        String loginRole = ApplicationUtil.getInstance().getLoginRole();
        if (context == null) {
            AlertDialogUtil.showAlertDialog(context, R.string.dialog_warning, R.string.SOMP_405);
            return false;
        } else if (CommonUtil.isNull(loginRole)) {
            AlertDialogUtil.showAlertDialog(context, R.string.dialog_warning, R.string.SB021_MSG015);
            return false;
        } else if (Constants.OWNER.equalsIgnoreCase(loginRole)) {
            return true;
        } else if (Constants.VISITOR.equalsIgnoreCase(loginRole)) {
            AlertDialogUtil.showAlertDialog(context, R.string.dialog_warning, R.string.SB021_MSG013,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            JoinMeUtils.checkVisitor(view);
                        }
                    }, true, R.string.upgrade_to_owner);
            return false;
        } else if (Constants.DRIVER.equalsIgnoreCase(loginRole) || Constants.PROXY.equalsIgnoreCase(loginRole)) {
            return true;
        }
        return false;
    }

    private boolean validateVehicleCommand() {
        if (!CommonUtil.checkNetWorkState(view.onActivity())) return false;
        if (!checkRole(view.onActivity())) return false;
        return !BusinessUtil.checkInProgressCommand(view.onActivity(), null);
    }

    private Subscription mPollingRx,mPinRx;

    public void registerRxBus() {
        mPollingRx = RxBus.getDefault().toObserverable(RxConstants.ALL_PAGE_ALERT, PollingResult.class)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<PollingResult>() {
            @Override
            public void call(PollingResult pollingResult) {
                if (view != null && view.onActivity() != null) {
                    RemoteCommandsType remotecommandType = RemoteCommandsType.fromValue(pollingResult.getRequestType());
                    view.setLoading(false);
                    if (remotecommandType == null) return;
                    switch (remotecommandType) {
                        case COMMAND_GETHOTSPOTINFO:
                            try {
                                if (RequestStatus.Failure.equals(RequestStatus.fromValue(pollingResult.getRequestStatus()))) {
                                    showError();
                                } else {
                                    view.onReponseSuccess(getWifiInfoModel(pollingResult));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                showError();
                            }
                            break;
                        case COMMAND_SETHOTSPOTINFO:
                            try {
                                if (RequestStatus.Failure.equals(RequestStatus.fromValue(pollingResult.getRequestStatus()))) {
                                    view.onResponseError(new OnStarException("", view.onActivity().getString(R.string.wifi_setinfo_failure)));
                                } else {
                                    view.onReponseSuccess(null);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                if (view != null && view.onActivity() != null) {
                                    view.onResponseError(new OnStarException("", view.onActivity().getString(R.string.wifi_setinfo_failure)));
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        });
        RxSubscriptions.add(mPollingRx);
    }

    private void showError() {
        if (view != null && view.onActivity() != null) {
            view.onResponseError(new OnStarException("", view.onActivity().getString(R.string.wifi_info_fetch_failure)));
//            view.onBack();
        }
    }

    private WifiInfoModel getWifiInfoModel(PollingResult result) throws Exception {
        String json = result.getJson();
        JSONObject jsonObject = GsonHelper.getJsonObject(json, "commandResponse");
        if (jsonObject == null) return null;
        if (RequestStatus.Success.getStringValue().equalsIgnoreCase(jsonObject.getString("status"))) {
            WifiInfoModel wifiInfoModel = new WifiInfoModel();
            JSONObject body = jsonObject.getJSONObject("body");
            if (!body.has("hotspotInfo")) {
                wifiInfoModel.setSsid(body.getString("ssid"));
                wifiInfoModel.setPassphrase(body.getString("passphrase"));
            } else {
                //IDT1个案处理
                wifiInfoModel.setSsid(body.getJSONObject("hotspotInfo").getString("ssid"));
                wifiInfoModel.setPassphrase(body.getJSONObject("hotspotInfo").getString("passphrase"));
            }
            return wifiInfoModel;
        } else {
            showError();
            return null;
        }
    }

    public void saveHotSpotInfo(FragmentManager fragmentManager, String ssid, String passphease, RemoteCommandsType commandsType) {
        if (CommonUtil.isNull(ssid)) {
            view.verifyResult(R.string.wifi_ssid_empty, false);
            return;
        }

        if(ApplicationUtil.getInstance().isCurrentInfo3Vehicle()){
            if (ssid.length() < 6 || ssid.length() > 14 || !CommonUtil.checkInputIncludeBlank(ssid)) {
                view.verifyResult(R.string.wifi_format_ssid_error, false);
                return;
            }
        }else {
            if (ssid.length() < 6 || ssid.length() > 18 || !CommonUtil.checkInputIncludeBlank(ssid)) {
                view.verifyResult(R.string.wifi_format_ssid_error, false);
                return;
            }
        }

        if (CommonUtil.isNull(passphease)) {
            view.verifyResult(R.string.wifi_pwd_empty, true);
            return;
        }
        if (passphease.length() < 8 || passphease.length() > 14 || !CommonUtil.checkInput(passphease)) {
            view.verifyResult(R.string.wifi_format_pwd_error, true);
            return;
        }
        //hotSpotInfo(ssid, passphease, commandsType);
        showPinOrNot(fragmentManager, ssid, passphease, commandsType);
    }

    public void hotSpotInfo(String ssid, String passphease, RemoteCommandsType commandsType) {
        if (!validateVehicleCommand()) {
//            view.onBack();
            return;
        }
        WifiInfoModel infoModel = new WifiInfoModel();
        infoModel.setSsid(ssid);
        infoModel.setPassphrase(passphease);
        infoModel.setRemoteCommandType(commandsType);
        view.setLoading(true);
        subscription = service.getHotSpotInfo(infoModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<WifiInfoModel>() {
                    @Override
                    public void call(WifiInfoModel s) {
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (view != null) {
                            view.onResponseError((OnStarException) throwable);
                            view.setLoading(false);
                        }
                    }
                });

    }


    public void showPinOrNot(FragmentManager fragmentManager, final String ssid, final String passphease, final RemoteCommandsType commandsType) {
        if (BusinessUtil.isAutoSendPin(commandsType, view.onActivity())) {
            hotSpotInfo(ssid, passphease, commandsType);
        } else {
            showPinDialogFragment(fragmentManager);

            /**
             * 从pin码页面返回
             */
            mPinRx =  RxBus.getDefault().toObserverable(RxConstants.WIFI_HOTSPOT, PinModel.class).filter(new Func1<PinModel, Boolean>() {
                @Override
                public Boolean call(PinModel pinModel) {
                    return pinModel.isPinSuccess();
                }
            }).subscribe(new Action1<PinModel>() {
                @Override
                public void call(PinModel pinModel) {
                    if (pinModel.isPinSuccess()) {
                        hotSpotInfo(ssid, passphease, commandsType);
                    } else {
                        if (view != null) {
                            view.setLoading(false);
                        }
                    }
                }
            });

            RxSubscriptions.add(mPinRx);
        }
    }

    private void showPinDialogFragment(FragmentManager fragmentManager) {
        PinDialogFragment pinDialogFragment = PinDialogFragment.newInstance(RemoteCommandsType.COMMAND_SETHOTSPOTINFO, RxConstants.WIFI_HOTSPOT);
        pinDialogFragment.show(fragmentManager, "pin_dialog");
    }

    public void stopPollingService(RemoteCommandsType remoteCommandsType) {
        Intent intent = new Intent(view.onActivity(), VehiclePollingService.class);
        view.onActivity().stopService(intent);
        service.stopPollingService(remoteCommandsType);
    }

    @Override
    public void finish() {
        super.finish();
        RxSubscriptions.remove(mPollingRx);
        RxSubscriptions.remove(mPinRx);
    }
}
